import React, { useState, useRef } from 'react';
import { useEffect } from 'react';
import style from './index.less';

// 导航栏数据
const navInfo = [
  {
    name: '产品说明',
    id: 'introduce',
    content: '这是产品说明',
  },
  {
    name: '使用指南',
    id: 'useFun',
    content: '这是使用指南',
  },
  {
    name: '售后服务',
    id: 'service',
    content: '这是售后服务',
  },
  {
    name: '产品参数',
    id: 'proParams',
    content: '这是产品参数',
  },
];

const TabAnchor = () => {
  const navContent = useRef(); // 标识nav导航栏渲染内容
  const [navList, setNavList] = useState(navInfo);
  const [fixNav, setFixnav] = useState(false); // 标识导航栏是否吸顶
  const [activeNav, setActiveNav] = useState(''); // 标识导航栏高亮

  useEffect(() => {
    // 增加滚动条监听事件
    document.addEventListener('scroll', scrollEventListener);
    return () => {
      document.removeEventListener('scroll', scrollEventListener);
    };
  }, []);

  const scrollEventListener = () => {
    // 获取导航栏显示内容区域信息
    const navContentReact = navContent.current.getBoundingClientRect();
    console.log(navContent.current);
    // 获取导航栏显示内容区域直接子元素
    const groupList = Array.from(navContent.current.children);

    if (navContentReact) {
      groupList.map((item) => {
        const itemReact = item.getBoundingClientRect();
        if (itemReact.y <= 60 && itemReact.y + itemReact.height > 60) {
          // 当该子元素距离顶部小于等于60s时,说明此时导航栏应该高亮
          // 同时在其高度范围内均应高亮
          setActiveNav(item.id);
        }
      });

      if (navContentReact.y <= 60) {
        setFixnav(true); // 吸顶
      } else if (navContentReact.y > 60) {
        setFixnav(false);
        setActiveNav('');
      }
    }
  };

  const onScrollInfoView = (id: React.SetStateAction<string>) => {
    setActiveNav(id);
    const targetDom = document.querySelector(`#${id}`);
    targetDom.scrollIntoView({
      behavior: 'smooth',
      block: 'start',
      inline: 'start',
    });
  };

  return (
    <div className={style.tabAnchorBox}>
      <div className={style.perch}>占位</div>
      <div>
        <div>
          <ul className={`${style.menu} ${fixNav ? style.active : ''}`}>
            {navList.map((item) => {
              return (
                <li key={item.id}>
                  <a
                    onClick={() => onScrollInfoView(item.id)}
                    className={`${
                      activeNav === item.id ? style.MenuActive : ''
                    }`}
                    href="#"
                  >
                    {item.name}
                  </a>
                </li>
              );
            })}
          </ul>
        </div>
        <div ref={navContent}>
          {navList.map((item) => {
            return (
              <div className={style.content} id={item.id} key={item.id}>
                <p>{item.name}</p>
                <p>{item.content}</p>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

export default TabAnchor;
